package me.maiz.babyisland.service.impl;

import me.maiz.babyisland.es.ProductRepository;
import me.maiz.babyisland.es.entity.ProductDocument;
import me.maiz.babyisland.service.SearchService;
import me.maiz.babyisland.es.ProductRepository;
import me.maiz.babyisland.es.entity.ProductDocument;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

@Service
public class SearchServiceImpl implements SearchService {

    /* 搜索模式 */
    String SCORE_MODE_SUM = "sum"; // 权重分求和模式
    Float MIN_SCORE = 10.0F;      // 由于无相关性的分值默认为 1 ，设置权重分最小值为 10


    @Autowired
    private ProductRepository productRepository;

    @Override
    public Page<ProductDocument> search(String kw, int categoryId, int pageIdx, int pageSize, String sort, String sortDirection) {

        // 分页参数
        Pageable pageable = PageRequest.of(pageIdx, pageSize);

        NativeSearchQueryBuilder qb = new NativeSearchQueryBuilder()
                .withPageable(pageable);

        if (StringUtils.isBlank(kw)) {
            qb.withQuery(QueryBuilders.matchAllQuery());
        } else {
            qb.withQuery(QueryBuilders.multiMatchQuery(kw)
                    .field("productName")
                    .field("description"));
        }
        if (StringUtils.isNotBlank(sort)) {
            qb.withSort(SortBuilders.fieldSort(sort).order(sortDirection.equalsIgnoreCase("desc") ? SortOrder.DESC : SortOrder.ASC));
        }


        SearchQuery query = qb
                .build();

        Page<ProductDocument> searchResult = productRepository.search(query);

        return searchResult;
    }
}
